package com.dy.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dy.common.R;
import com.dy.common.RedisConstonts;
import com.dy.dto.DishDto;
import com.dy.entity.Dish;
import com.dy.entity.DishFlavor;
import com.dy.mapper.DishMapper;
import com.dy.service.DishFlavorService;
import com.dy.service.DishService;
import com.dy.utils.Oss_chengdu_blog;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author dy
 * @Description: 菜品 服务实现类
 */
@Slf4j
@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private StringRedisTemplate strRedis;
    /**
     * @Author dy
     * @Description:  新增保存菜品，和口味
     */
    @Transactional
    public R<String> saveDishAndFlavor(DishDto dishDto) {
        //新增菜品
        boolean save = this.save(dishDto);
        if(BooleanUtil.isFalse(save)){
            return R.error("新增失败，请重试 /(ㄒoㄒ)/~~");
        }
        //给当前新增菜品  新增口味。
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors = flavors.stream().map(flavor->{
            flavor.setDishId(dishDto.getId());
            return flavor;
        }).collect(Collectors.toList());

        //新增口味
        boolean b = dishFlavorService.saveBatch(flavors);
        if(BooleanUtil.isFalse(b)){
            return R.success("新增成功，就是没加口味 /(ㄒoㄒ)/~~");
        }

        //新增完删除菜品对应分类缓存
        strRedis.delete(RedisConstonts.DISH_LIST + dishDto.getCategoryId() + "_" + "1");

        return R.success("新增菜品成功");
    }


    /**
     * @Author dy
     * @Description: 查找菜品集合
     */
    public List<DishDto> getDishList(Integer page, Integer pageSize, String name) {
        return dishMapper.getDishList(page,pageSize,name);
    }


    /**
     * @Author dy
     * @Description: 根据ID 查询菜品
     */
    public R<DishDto> findById(Long id) {
        DishDto dishDto = new DishDto();
        //根据ID获取口味数据
        Dish dish = this.getById(id);
        //拷贝元数据
        BeanUtil.copyProperties(dish,dishDto);

        //查找对应的 菜品口味
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(DishFlavor::getDishId,id);
        List<DishFlavor> list = dishFlavorService.list(queryWrapper);

        dishDto.setFlavors(list);
        //返回数据

        return R.success(dishDto);
    }

    @Transactional
    public R<String> updateDish(DishDto dishDto) {
        //修改菜品数据
        this.updateById(dishDto);

        //修改对应菜品的 口味
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors = flavors.stream().map(flavor -> {
            flavor.setDishId(dishDto.getId());
            return flavor;
        }).collect(Collectors.toList());

        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(DishFlavor::getDishId,dishDto.getId());
        //先删除 原有的口味
        dishFlavorService.remove(queryWrapper);
        //新增 刚修改的 口味
        dishFlavorService.saveBatch(flavors);

        //修改完删除菜品对应分类缓存
        strRedis.delete(RedisConstonts.DISH_LIST + dishDto.getCategoryId() + "_" + "1");
        return R.success("修改成功");
    }


    /**
     * @Author dy
     * @Description: 修改菜品状态  0:停售 1：起售
     */
    @Transactional
    public R<String> updateStatus(Integer status, List<Long> ids) {
        //获取 菜品集合
        List<Dish> collect = ids.stream().map(id -> {
            Dish dish = new Dish();
            dish.setId(id);
            dish.setStatus(status);
            return dish;
        }).collect(Collectors.toList());
        boolean b = this.updateBatchById(collect);

        if(BooleanUtil.isTrue(b)){
            //修改成功，清除对应菜品分类缓存
            LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper();
            queryWrapper.select(Dish::getCategoryId);
            queryWrapper.in(Dish::getId,ids);
            queryWrapper.groupBy(Dish::getCategoryId);
            //获取修改状态的每个菜品对应的分类ID
            List<Dish> list = this.list(queryWrapper);

            for (Dish dish : list) {
                //修改完状态删除菜品对应分类缓存
                strRedis.delete(RedisConstonts.DISH_LIST + dish.getCategoryId() + "_" + "1");
            }
            return R.success("修改成功 (*^_^*)");
        }
        return R.error("修改失败");
    }


    /**
     * @Author dy
     * @Description: 删除菜品/ 对应口味
     */
    @Transactional
    public R<String> deleteDish(Long[] ids) {
        //过滤 判断删除菜品是否启售
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper();
        wrapper.in(Dish::getId,ids);
        wrapper.eq(Dish::getStatus,1);
        int count = this.count(wrapper);
        if(count > 0){
            return R.error("当前菜品正在销售，请停售后删除。");
        }
        //获取要删除的 菜品图片路径
        List<String> fileName = dishMapper.getFileName(ids);
        //删除对应OSS 保存的图片
        Oss_chengdu_blog.deleteFile(fileName);

        //删除对应菜品分类的redis缓存
        LambdaQueryWrapper<Dish> apper = new LambdaQueryWrapper();
        apper.select(Dish::getCategoryId);
        apper.in(Dish::getId,ids);
        apper.groupBy(Dish::getCategoryId);
        List<Dish> list = this.list(apper);

        //获取删除的每个菜品对应的分类ID
        for (Dish dish : list) {
            //修改完状态删除菜品对应分类缓存
            strRedis.delete(RedisConstonts.DISH_LIST + dish.getCategoryId() + "_" + "1");
        }

        //删除菜品
        List<Long> longs = Arrays.asList(ids);
        boolean boo1 = this.removeByIds(longs);
        if(BooleanUtil.isFalse(boo1)){
            return R.error("删除失败，请重试。");
        }
        //删除对应口味
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.in(DishFlavor::getDishId,longs);
        dishFlavorService.remove(queryWrapper);

        return R.success("删除成功");
    }

    //获取菜品总数
    public Long getTotal(String name) {
        Long total = dishMapper.getTotal(name);
        return total;
    }
}
